package com.zhangshuo.patternDesign.resrponsibility;

import java.util.Map;

/**
 * Created by shuo.zhang on 2017-10-28.
 * <p>
 * 分店的抽象类
 */
public class McSubbranch implements IMcSubbranch {

    /**
     * 分店号
     */
    private int num;
    /**
     * 坐标
     */
    private int x;
    private int y;
    /**
     * 菜单列表
     */
    private Map<String, Integer> menu;
    /**
     * 计数器
     */
    private static int count = 0;

    private IMcSubbranch successor;
    /**
     * 最远配送距离
     */
    private static final int MAX_DISTANCE = 50;

    public McSubbranch(int num, int x, int y) {
        this.num = num;
        this.x = x;
        this.y = y;
    }


    public McSubbranch(int x, int y, Map<String, Integer> menu) {
        this.x = x;
        this.y = y;
        this.menu = menu;
        this.num = ++count;
    }


    public IMcSubbranch getSuccessor() {
        return successor;
    }

    @Override
    public void setSuccessor(IMcSubbranch iMcSubbranch) {
        this.successor = iMcSubbranch;

    }

    /**
     * 检验订单是否OK
     *
     * @param order
     * @return
     */
    private boolean checkOrder(Order order) {

        return checkInstance(order.getX(), order.getY(), this.x, this.y) && checkMenu(order.getOrderMap());
    }

    /**
     * 验证余量是否充足
     *
     * @param orderMap
     * @return
     */
    private boolean checkMenu(Map<String, Integer> orderMap) {
        int enoughCount = (int) orderMap.keySet().stream().filter(dish ->
                this.menu.containsKey(dish) && menu.get(dish) >= orderMap.get(dish)).count();
        boolean result = enoughCount == orderMap.size();
        return result;
    }

    /**
     * 距离是不否符合要求
     *
     * @param x1
     * @param y
     * @return
     */
    private boolean checkInstance(int x1, int y1, int x2, int y2) {

        boolean result = CommonUtils.instanceLessThan(x1, y1, x2, y2, MAX_DISTANCE);
        return result;
    }


    @Override
    public synchronized boolean handleOrder(Order order) {

        if (checkOrder(order)) {
            System.out.println("订单已接收到..................");
            order.getOrderMap().keySet().stream().forEach((dish) -> {
                this.menu.put(dish, menu.get(dish) - order.getOrderMap().get(dish));
                System.out.println("在第" + this.num + "家店订购" + dish + "数量为 " + order.getOrderMap().get(dish));
            });
            return true;
        }

        if (successor == null)
            return false;



        return successor == null ? false: successor.handleOrder(order);

//        return successor.handleOrder(order);
    }
}
